package com.lut.reservation.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lut.reservation.bean.Room;
import com.lut.reservation.bean.RoomComment;
import com.lut.reservation.bean.RoomReservation;
import com.lut.reservation.service.RoomCommentService;
import com.lut.reservation.service.RoomReservationService;
import com.lut.reservation.service.RoomService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import java.util.Date;
import java.util.List;

/**
 * @Author: zyt
 */
@Controller
@RequestMapping
public class HomeController {

  @Autowired
  private RoomService roomService;

  @Autowired
  private RoomCommentService commentService;

  @Autowired
  private RoomReservationService reservationService;

  @GetMapping("/detail")
  public ModelAndView detail(String id, ModelAndView mv) {
    final Room room = roomService.getById(id);
    final List<RoomComment> commentList = commentService.lambdaQuery()
        .eq(RoomComment::getState, "PASS")
        .eq(RoomComment::getRoomId, id)
        .orderByDesc(RoomComment::getTime)
        .list();
    final List<RoomReservation> reservationList = reservationService.lambdaQuery()
        .eq(RoomReservation::getRoomId, id)
        .in(RoomReservation::getState, "PASS", "INIT")
        .gt(RoomReservation::getEndTime, new Date())
        .orderByAsc(RoomReservation::getStartTime)
        .list();
    reservationList.forEach(reservation -> {
      final long startTime = reservation.getStartTime().getTime();
      final long endTime = reservation.getEndTime().getTime();
      final long currentTime = System.currentTimeMillis();
      reservation.setSt(currentTime > startTime && currentTime < endTime);
    });
    mv.addObject("room", room);
    mv.addObject("commentList", commentList);
    mv.addObject("reservationList", reservationList);
    mv.setViewName("home/roomDetail");
    return mv;
  }

  @GetMapping("page")
  public ModelAndView page(@RequestParam(defaultValue = "1") Integer current, @RequestParam(defaultValue = "10") Integer limit, ModelAndView mv) {
    final Page<Room> page = roomService.page(new Page<>(current, limit));
    mv.addObject("roomList", page.getRecords());
    mv.addObject("count", page.getTotal());
    mv.setViewName("home/roomPage");
    return mv;
  }


}
